const webpack = require('webpack') 
const Config = require('webpack-chain') 
const chalk = require('chalk')
const { resolveAlias, resolveLoaders, resolveModules, moduleRules, mapExternals, root, loadConfig, mergeJmConfig } = require('./util')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { resolve } = require('path')

async function packWebpack(coms=[], buildConfig) { 

  const jmConfig = await loadConfig(buildConfig)

  const webpackConfigs = coms.map(com=> { 
    const config = new Config() 

    config.entry('index').add(resolve(com.dir, 'index.js')) 

    moduleRules(config)

    resolveModules(config)

    resolveAlias(config)

    resolveLoaders(config)

    externals(config)
    config.output.path(resolve(root, 'dist', com.name, com.version))
    config.output.filename('index.js')
    config.output.libraryTarget('umd')
    config.output.libraryExport('default')

    let patterns = []
    if (com.hasXml) {
      patterns.push({
        from: resolve(com.dir, 'config.xml'), 
        to: '' 
      })
    }
    if (com.hasFreeLayoutXml) {
      patterns.push({
        from: resolve(com.dir, 'freeLayoutConfig.xml'), 
        to: '' 
      })
    }
    if (com.hasStatic) {
      patterns.push({
        from: resolve(com.dir, 'static'), 
        to: 'static' 
      })
    }
    if(com.hasXml || com.hasStatic || com.hasFreeLayoutXml) { 
      config.plugin('copy').use(CopyWebpackPlugin, [{ 
        patterns,
      }]) 
    } 
    // if(com.hasXml) { 
    //   config.plugin('copy').use(CopyWebpackPlugin, [{ 
    //     patterns: [{ 
    //       from: resolve(com.dir, 'config.xml'), 
    //       to: '' 
    //     }] 
    //   }]) 
    // }
    config.plugin('chunkPlugin').use(webpack.optimize.LimitChunkCountPlugin,[{
      maxChunks: 1,
    }])

    mergeJmConfig(config, jmConfig)

    return config.toConfig() 
  }) 

  // 打包构建
  await new Promise((resolve,reject)=> {
    webpack(webpackConfigs, (err, stats)=> {
      if(stats.hasErrors()) {
        // console.error(stats.compilation.getErrors())
        const info = stats.toJson()
        console.error(info.errors)
        
        console.error(chalk.redBright('编译异常'))

        resolve()
      } else if(err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })

  // 生成压缩包
  
} 

function externals(config) { 
  config.externals( 
    mapExternals([ 
      'yt-engine', 
      'vue', 
      'vue-styled-components', 
      'ant-design-vue', 
      'echarts', 
      'jquery', 
      'moment', 
      'echarts-wordcloud',
      'react',
      'react-dom'
    ]) 
  ) 

  return config 
} 

module.exports = { 
  packWebpack 
} 
